/**
 * n-page
 * author: 'byhgj'
 * git: https://gitee.com/byhgj/n-page.git
 */
class nPage {
	constructor(opts){
		this.start = opts.start || 0;
		this.limit = opts.limit || 20;
		this._count = opts.count || 100;
		this.handler = opts.handler || function(){};

		this._from = this.start + 1;
		this._to = this._from + this.limit - 1;

		this.status = {
			first: true,
			prev: true,
			next: true,
			last: true
		}
		//this._refreshStatus();
		//this.handler(this.start);
		if (opts.autoboot === true)
			this.refresh()
	}
	get from() {
		return this._from;
	}
	get to() {
		return this._to;
	}
	get count(){
		return this._count;
	}
	set count(v){
		this._count = v;
		this._refreshStatus();
	}
	_refreshStatus(){
		this._from = this.start  + 1;
		this._to = this._from + this.limit - 1;
		if (this._to > this.count) this._to = this.count;
		
		this.status.first = this.start !== 0;
		this.status.prev = this.start !== 0;
		this.status.next = this.start + this.limit < this.count;
		this.status.last = this.start + this.limit < this.count;		
	}
	first(){
		if (this.start === 0) return;
		this.start = 0;
		this._refreshStatus();
		this.handler(this.start);
	}
	prev(){
		if (this.start - this.limit < 0) return;
		this.start -= this.limit;
		this._refreshStatus();
		this.handler(this.start);
	}
	next(){
		if (this.start + this.limit >= this.count) return;
		this.start += this.limit;
		this._refreshStatus();
		this.handler(this.start);
	}
	last(){
		if (this.start + this.limit >= this.count) return;
		this.start = this.limit*Math.floor((this.count-1)/this.limit);
		this._refreshStatus();
		this.handler(this.start);
	}
	refresh(){
		this._refreshStatus();
		this.handler(this.start);
	}
}

(function(){
	window.npage = function(opts){
		return new nPage(opts);
	}
})();